package com.ogilvy.cms.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.ogilvy.cms.bean.CmsLog;
import com.ogilvy.cms.bean.CmsTemplateField;
import com.ogilvy.cms.bean.CmsUser;
import com.ogilvy.cms.util.ServiceDispatcher;
import com.ogilvy.common.JSONBean;
import com.ogilvy.common.MetaData;
import com.ogilvy.common.UtilTools;

@SuppressWarnings("serial")
@Scope("prototype")
@Controller("cms.action.CmsTemplateFieldAction")
public class CmsTemplateFieldAction extends AdminAction{
	private static final Logger log = LoggerFactory.getLogger(CmsTemplateFieldAction.class);
	@Autowired
	protected ServiceDispatcher serviceDispatcher;
	//protected templatefieldService templatefieldService;
	private String rows;//前台以JSON的形式传递数据
	private int start;//分页开始
	private int limit;//每页显示量
	public String getRows() {
		return rows;
	}
	public void setRows(String rows) {
		this.rows = rows;
	}
	public int getStart() {
		return start;
	}
	public void setStart(int start) {
		this.start = start;
	}
	public int getLimit() {
		return limit;
	}
	public void setLimit(int limit) {
		this.limit = limit;
	}
	//点击左边树的跳转
	public String index(){
		return "index";
	}
	private CmsTemplateField temField=new CmsTemplateField();
	List<CmsTemplateField> templatefieldlist;
	//List<CmsTemplate> templist;
	/**到列表页面*/
	public void query(){
		if(rows==null){
			templatefieldlist=serviceDispatcher.getCmsTemplateFieldService().query(temField);
		}else{
			net.sf.json.JSONObject js = net.sf.json.JSONObject.fromObject(rows);
			Map<String,String> screenMap=new HashMap<String, String>();
			screenMap.put("ctfCmtId", js.getString("ctfCmtId"));
			templatefieldlist=serviceDispatcher.getCmsTemplateFieldService().queryByScreen(screenMap);
		}
		
		//采用集合分页
		List pageList = UtilTools.queryForPage(start, limit, templatefieldlist);
		JSONBean jbean = new JSONBean();
		MetaData md = new MetaData();
		
		md.setIdProperty("ctfId");//关联将要显示列表对应的bean实体的主键ID
		md.reflectFields("com.ogilvy.cms.bean.CmsTemplateField");//关联将要显示列表对应的bean实体
		jbean.setMetaData(md);
		jbean.setRows(pageList);
		jbean.setSuccess(true);
		jbean.setTotal(templatefieldlist.size());
		
		ServletActionContext.getResponse().setCharacterEncoding("UTF-8");
		
		String jsonString = UtilTools.encodeObject2Json(jbean,"MM/dd/yyyy HH:mm:ss");
		PrintWriter out;
		try {
			out = ServletActionContext.getResponse().getWriter();
			out.print(jsonString);
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**添加*/
	public void add(){
		ServletActionContext.getResponse().setCharacterEncoding("UTF-8");
		net.sf.json.JSONObject js = net.sf.json.JSONObject.fromObject(rows);
		String template=js.getString("ctfCmtId");
		int ctfCmtId=Integer.parseInt(template);
		String ctfViewName=js.getString("ctfViewName");
		String ctfName=js.getString("ctfName");
		String ctfType=js.getString("ctfType");
		String leng=js.getString("ctfLength");
		int ctfLength=Integer.parseInt(leng);
		String ctfWidth=js.getString("ctfWidth");
		String ctfHeight=js.getString("ctfHeight");
		String order=js.getString("ctfOrderNum");
		int ctfOrderNum=Integer.parseInt(order);
		String ctfSiteType=js.getString("ctfSiteType");
		
		CmsUser cmsuser = getCmsUser();
		String ctfLastuser =cmsuser.getCmuName();//获取session中对象的姓名

		Date ctfLasttime=new Date();
		
		temField.setCtfCmtId(ctfCmtId);
		temField.setCtfViewName(ctfViewName);
		temField.setCtfName(ctfName);
		temField.setCtfType(ctfType);
		temField.setCtfLength(ctfLength);
		temField.setCtfWidth(ctfWidth);
		temField.setCtfHeight(ctfHeight);
		temField.setCtfOrderNum(ctfOrderNum);
		temField.setCtfSiteType(ctfSiteType);
		temField.setCtfLastuser(ctfLastuser);
		temField.setCtfLasttime(ctfLasttime);
		
		boolean isHave=serviceDispatcher.getCmsTemplateFieldService().checkTempFieldName(ctfName);
		if(isHave==false){
			CmsTemplateField ctf=serviceDispatcher.getCmsTemplateFieldService().add(temField);
			JSONBean bean = new JSONBean();
			bean.setSuccess(true);
			// 需要新建一个具有id的vo返回给前台以便通知前台保存成功，不然前台一直处于编辑状态
			List rows = new ArrayList();
			rows.add(ctf);
			bean.setRows(rows);
			//String jsonString = UtilTools.encodeObject2Json(bean);
			String jsonString = UtilTools.encodeObject2Json(bean,"MM/dd/yyyy HH:mm:ss");
			/**
			 * 系统操作日志
			 */
			CmsLog  log = UtilTools.buildLog("模板字段定义", CmsLog.Add, "添加模板字段", ctfLastuser);
	        serviceDispatcher.getCmsLogService().add(log);
			PrintWriter out;
			try {
				out = ServletActionContext.getResponse().getWriter();
				out.print(jsonString);
				out.flush();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			StringBuffer jsonString =new StringBuffer();
            jsonString.append("{");
            jsonString.append("success:true,");
            jsonString.append("isHave:true,");
            jsonString.append("msg:'对不起,该字段名已存在!'");
            jsonString.append("}");
        	 PrintWriter out;
 	        try {
 	            out = ServletActionContext.getResponse().getWriter();
 	            out.print(jsonString);
 	            out.flush();
 	            out.close();
 	        } catch (IOException e) {
 	            e.printStackTrace();
 	        }
		}
		
		
	}
	/**删除*/
	public void del(){
		net.sf.json.JSONArray objArr = net.sf.json.JSONArray.fromObject(rows);
		for(int i=0;i<objArr.size();i++)
		{
			net.sf.json.JSONObject js=objArr.getJSONObject(i);
			String ctfID=js.getString("ctfId");
			int ctfId=Integer.valueOf(ctfID);
			serviceDispatcher.getCmsTemplateFieldService().del(ctfId);
		}
		JSONBean bean = new JSONBean();
		bean.setSuccess(true);
		//String jsonString = UtilTools.encodeObject2Json(bean);
		String jsonString = UtilTools.encodeObject2Json(bean,"MM/dd/yyyy HH:mm:ss");
		
		CmsUser cmsuser = getCmsUser();
		String ctfLastuser =cmsuser.getCmuName();//获取session中对象的姓名
		/**
		 * 系统操作日志
		 */
		CmsLog  log = UtilTools.buildLog("模板字段定义", CmsLog.DELETE, "删除模板字段", ctfLastuser);
        serviceDispatcher.getCmsLogService().add(log);
		PrintWriter out;
		try {
			out = ServletActionContext.getResponse().getWriter();
			out.print(jsonString);
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**修改*/
	public void modify(){
		ServletActionContext.getResponse().setCharacterEncoding("UTF-8");
		net.sf.json.JSONObject js = net.sf.json.JSONObject.fromObject(rows);
		String fieldId=js.getString("ctfId");
		int ctfId=Integer.parseInt(fieldId);
		String template=js.getString("ctfCmtId");
		int ctfCmtId=Integer.parseInt(template);
		String ctfViewName=js.getString("ctfViewName");
		String ctfName=js.getString("ctfName");
		String copyCtfName=js.getString("copyCtfName");
		String ctfType=js.getString("ctfType");
		String leng=js.getString("ctfLength");
		int ctfLength=Integer.parseInt(leng);
		String ctfWidth=js.getString("ctfWidth");
		String ctfHeight=js.getString("ctfHeight");
		String order=js.getString("ctfOrderNum");
		int ctfOrderNum=Integer.parseInt(order);
		String ctfSiteType=js.getString("ctfSiteType");
		CmsUser cmsuser = getCmsUser();
		String ctfLastuser =cmsuser.getCmuName();//获取session中对象的姓名
		
		Date ctfLasttime=new Date();
		
		temField.setCtfId(ctfId);
		temField.setCtfCmtId(ctfCmtId);
		temField.setCtfViewName(ctfViewName);
		temField.setCtfName(ctfName);
		temField.setCtfType(ctfType);
		temField.setCtfLength(ctfLength);
		temField.setCtfWidth(ctfWidth);
		temField.setCtfHeight(ctfHeight);
		temField.setCtfOrderNum(ctfOrderNum);
		temField.setCtfSiteType(ctfSiteType);
		temField.setCtfLastuser(ctfLastuser);
		temField.setCtfLasttime(ctfLasttime);
		
		if(copyCtfName.equals(ctfName)){
			serviceDispatcher.getCmsTemplateFieldService().modify(temField);
			JSONBean bean = new JSONBean();
			bean.setSuccess(true);
			//String jsonString = UtilTools.encodeObject2Json(bean);
			String jsonString = UtilTools.encodeObject2Json(bean,"MM/dd/yyyy HH:mm:ss");
			/**
			 * 系统操作日志
			 */
			CmsLog  log = UtilTools.buildLog("模板字段定义", CmsLog.MODIFY, "修改模板字段", ctfLastuser);
	        serviceDispatcher.getCmsLogService().add(log);
			PrintWriter out;
			try {
				out = ServletActionContext.getResponse().getWriter();
				out.print(jsonString);
				out.flush();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 }else{
			 boolean isHave=serviceDispatcher.getCmsTemplateFieldService().checkTempFieldName(ctfName);
			 if(isHave==false){
				 serviceDispatcher.getCmsTemplateFieldService().modify(temField);
					JSONBean bean = new JSONBean();
					bean.setSuccess(true);
					//String jsonString = UtilTools.encodeObject2Json(bean);
					String jsonString = UtilTools.encodeObject2Json(bean,"MM/dd/yyyy HH:mm:ss");
					/**
					 * 系统操作日志
					 */
					CmsLog  log = UtilTools.buildLog("模板字段定义", CmsLog.MODIFY, "修改模板字段", ctfLastuser);
			        serviceDispatcher.getCmsLogService().add(log);
					PrintWriter out;
					try {
						out = ServletActionContext.getResponse().getWriter();
						out.print(jsonString);
						out.flush();
						out.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			 }else{
				    StringBuffer jsonString =new StringBuffer();
		            jsonString.append("{");
		            jsonString.append("success:true,");
		            jsonString.append("isHave:true,");
		            jsonString.append("msg:'对不起,该字段名已存在!'");
		            jsonString.append("}");
		        	 PrintWriter out;
		 	        try {
		 	            out = ServletActionContext.getResponse().getWriter();
		 	            out.print(jsonString);
		 	            out.flush();
		 	            out.close();
		 	        } catch (IOException e) {
		 	            e.printStackTrace();
		 	        }
			 }
		 }
	}
	
	/**
	 * 根据cmtId查询子表信息
	 */
	public void queryByCmtId(){
		net.sf.json.JSONObject js = net.sf.json.JSONObject.fromObject(rows);
		int cmtId = Integer.parseInt(js.getString("cmtId"));
		templatefieldlist=serviceDispatcher.getCmsTemplateFieldService().selectTemplateFieldByCmtId(cmtId);
		
		List pageList = UtilTools.queryForPage(start, limit, templatefieldlist);
		JSONBean jbean = new JSONBean();
		MetaData md = new MetaData();
		md.setIdProperty("ctfId");//关联将要显示列表对应的bean实体的主键ID
		md.reflectFields("com.ogilvy.cms.bean.CmsTemplateField");//关联将要显示列表对应的bean实体
		jbean.setMetaData(md);
		jbean.setRows(pageList);
		jbean.setSuccess(true);
		jbean.setTotal(templatefieldlist.size());
		ServletActionContext.getResponse().setCharacterEncoding("UTF-8");
		String jsonString = UtilTools.encodeObject2Json(jbean,"MM/dd/yyyy HH:mm:ss");
		PrintWriter out;
		try {
			out = ServletActionContext.getResponse().getWriter();
			out.print(jsonString);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
